<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/welcom' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>权限管理</el-breadcrumb-item>
		  <el-breadcrumb-item>角色列表</el-breadcrumb-item>
		</el-breadcrumb>
		<el-card class="box-card">		
			<el-row>
				<el-col>
				  <el-button type="primary" @click='handleOpenAddRole'>添加角色</el-button>
				  <el-dialog
				    title="添加角色"
				    :visible.sync="centerDialogVisible"
				    width="30%"
				    center>
					<el-form :model="addRoleForm" :rules="rules" ref="addRoleForm" label-width="80px">
						 <el-form-item label="角色名称" prop="addRoleName">
						    <el-input v-model="addRoleForm.addRoleName"></el-input>
						  </el-form-item>
						  <el-form-item label="角色描述" prop="addRoleDesc">
						     <el-input type="textarea" rows="4" v-model="addRoleForm.addRoleDesc"></el-input>
						   </el-form-item>
					</el-form>
					<span slot="footer" class="dialog-footer">
					<el-button type="primary" @click="addRoleSubmit('addRoleForm')">确 认</el-button>
					<el-button @click="resetForm('addRoleForm')">重 置</el-button>
					</span>
				  </el-dialog>
				</el-col>
			</el-row>
			<el-table :data="rolelist" border stripe>
				<!-- 展开列 -->
				<el-table-column type="expand" >
					<template slot-scope="scope">
						<el-row :class="['bd-bottom',i1 === 0 ? 'bd-top' :'','vcenter']" v-for=" (item1,i1) in scope.row.children" :key="item1.id">
							<!-- 渲染一级权限 -->
							<el-col :span="5">
								<el-tag  @close="removeById(scope.row,item1.id)" closable>{{item1.authName}}</el-tag>
								<i class="el-icon-caret-right"></i>
							</el-col>
							<!-- 渲染二，三级权限 -->
							<el-col :span="19">
								<!-- 循环渲染二级权限 -->
								 <el-row :class="[i2 === 0 ? '':'bd-top','vcenter']" v-for="(item2,i2) in item1.children" :key="item2.id">
									 <el-col :span="5">
										 <el-tag  type="success"  @close="removeById(scope.row,item2.id)" closable>{{item2.authName}}</el-tag>
										 <i class="el-icon-caret-right"></i>
									 </el-col>
									 <el-col :span="19">
										 <el-tag type="warning" v-for="item3 in item2.children" :key="item3.id" @close="removeById(scope.row,item3.id)" closable>{{item3.authName}}</el-tag>
									 </el-col>
								 </el-row>
							</el-col>
						</el-row>
					</template>
				</el-table-column>
				
				<!-- 索引列 -->
				<el-table-column type="index"></el-table-column>
				<el-table-column label="角色名称" prop="roleName"></el-table-column>
				<el-table-column label="角色描述" prop="roleDesc"></el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-tooltip content="修改描述"  :enterable='false' placement="top">
						   <el-button @click="roleInfo(scope.row)" type="primary" icon="el-icon-edit"  size="mini" circle></el-button>
						</el-tooltip>
						<el-tooltip content="删除角色"  :enterable='false' placement="top">
						   <el-button @click="deleteRole(scope.row)" type="danger" icon="el-icon-delete"  size="mini" circle></el-button>
						</el-tooltip>
						<el-tooltip content="分配权限"  :enterable='false' placement="top">
						<el-button  @click="disRoles(scope.row)" type="warning" icon ="el-icon-setting"  size="mini" circle></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
			</el-table>
		</el-card>
		<!-- 分配权限对话框 -->
		<el-dialog
		  title="权限设置"
		  :visible.sync="disDialogVisible"
		  width="30%"
		  @close="disDialogClosed"
		  >
		  <span>所有权限列表</span>
		  <!-- 树形控件 -->
		  <el-tree :data="rightslist" 
		  :props="treeProps"
		  ref="treeRef"
		  node-key="id"
		  default-expand-all
		  :default-checked-keys="defKeys"
		  show-checkbox>
		   </el-tree>


		  <span slot="footer" class="dialog-footer">
		    <el-button @click="disDialogVisible = false">取 消</el-button>
		    <el-button type="primary"  @click="allotRights">确 定</el-button>
		  </span>
		</el-dialog>

        <el-dialog title="角色信息"
		  :visible.sync="roleInfoDialogVisible"
		  width="30%"
		  @close="disDialogClosed"
		  >
		  <el-form ref="roleForm" :model="roleForm" label-width="80px">
			  <el-form-item label="角色名称">
			      <el-input v-model="roleForm.roleName"  disabled></el-input>
			    </el-form-item>
				<el-form-item label="角色描述">
				    <el-input type="textarea" v-model="roleForm.roleDesc"></el-input>
				  </el-form-item>
           </el-form>
		   <span slot="footer" class="dialog-footer">
		     <el-button @click="roleInfoDialogVisible = false">取 消</el-button>
		     <el-button type="primary"  @click="changeRoleDesc">确 定</el-button>
		   </span>
		</el-dialog>
	</div>
</template>

<script>
	export default{
		data(){
			return {
				//角色列表
				rolelist:[],
				//权限列表
				rightslist:[],
				// 默认选中的权限id数组
				defKeys:[],
				//权限id字符串
				roleId:'',
				roleForm:[],
				treeProps:{
					label:'authName',
					children:'children'
				},
				centerDialogVisible:false,
				disDialogVisible:false,
				roleInfoDialogVisible:false,
				addRoleForm:{
					addRoleName:'',
					addRoleDesc:''
				},
				rules:{
					addRoleName: [
                { required: true, message: '请输入活动名称', trigger: 'blur' },
                { min: 2, max: 15, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
				addRoleDesc	: [
                { required: false, message: '请输入活动名称', trigger: 'blur' },
                { min: 0, max: 99, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ],
				}
			}
		},
		created() {
			this.getRoleList()
		},
		methods:{
			handleOpenAddRole(){
				this.centerDialogVisible = 'true'
			},
			addRoleSubmit(addRoleForm){
				this.$refs[addRoleForm].validate( async (valid) => {
					if (valid){
										const {data: res} = await this.$http.post('roles',{roleName:this.addRoleForm.addRoleName,roleDesc:this.addRoleForm.addRoleDesc})
										console.log(res)
										if(res.meta.status !== 201)
										{
										return this.$message.error(res.meta.msg)
										}
										this.centerDialogVisible = false
										this.getRoleList()
										this.$refs[addRoleForm].resetFields();
										return this.$message.success(res.meta.msg)
											
										
									}
				});
				
			},
			  resetForm(addRoleForm) {
			        this.$refs[addRoleForm].resetFields();
			      },
			async getRoleList(){
				const { data: res } = await this.$http.get('roles')
				if ( res.meta.status !== 200 ) {
					return this.$message.error('获取角色列表失败！')
				}
				
				this.rolelist = res.data
				
				console.log(this.rolelist)
			},
			//按照id删除权限
			async removeById(role,rightId){
				const confirmResult = await  this.$confirm(
				         '此操作将永久删除该权限, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning'
				        }
						).catch( err => err)
						
						if( confirmResult !== "confirm" )
						{
							return this.$message.info('取消成功')
						}
						
					const {data:res} = await this.$http.delete('roles/'+role.id+'/rights/'+rightId)
						
						if(res.meta.status !== 200)
						{
						return this.$message.error('删除权限失败!')
						}
						this.$message.success('删除权限成功！')
						console.log(res.data)
						role.children = res.data
						
				
			},
			//删除指定角色
			async deleteRole(role){
				const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning',
						  }).catch( err => err )
						  
				if( confirmResult !== "confirm" )
				return this.$message.info('取消成功！')
				//console.log(role)
				const { data:res } = await this.$http.delete('roles/'+role.id)
				//console.log(res)
				if( res.meta.status !== 200 )
				return this.$message.error('删除失败！')
				
				this.$message.success('删除成功！')
				return  this.getRoleList()
			},
			async disRoles(role){
			  this.roleId = role.id
			  const { data:res } = await this.$http.get('rights/tree')
			  console.log(res)
			  if( res.meta.status !== 200 )
			  return this.$message.error(res.meta.msg)
			  this.rightslist = res.data
			  this.getRoleArr(role,this.defKeys)
			  this.disDialogVisible = true
			},
			getRoleArr(node,arr){
				if( !node.children )
				return arr.push(node.id)
				
				node.children.forEach( item => this.getRoleArr(item,arr) )
			},
			//监听对话框关闭
			disDialogClosed(){
				this.defKeys=[]
			},
			//分配权限函数
			async allotRights(){
				const keys = [
					...this.$refs.treeRef.getCheckedKeys(),
					...this.$refs.treeRef.getHalfCheckedKeys()
				]
				//console.log(keys)
				const idStr = keys.join(',')
				
				const { data:res } = await this.$http.post('roles/'+this.roleId+'/rights',{ rids:idStr })
				//console.log(res)
				if( res.meta.status !==200 )
				return this.$message.error('更新失败！')
				
				this.$message.success('更新成功！')
				this.getRoleList()
				this.disDialogVisible = false
				
			},
			//角色信息对话框
			roleInfo(role){
				this.roleInfoDialogVisible = true
				this.roleForm = role
				//console.log(this.roleForm)
			},
			//修改角色描述
			async changeRoleDesc(){
				console.log(this.roleForm.roleName)
				const { data:res } = await this.$http.put('roles/'+this.roleForm.id,{ roleName :this.roleForm.roleName,roleDesc:this.roleForm.roleDesc })
				console.log(res)
				if( res.meta.status !==200 )
				return this.$message.error('更新失败！')
				
				this.$message.success('更新成功！')
				this.getRoleList()
				this.roleInfoDialogVisible = false
			}
		}
	}
</script>

<style  lang="less" scoped>
	.el-tag{
		margin: 7px;
	}
	.bd-top{ border-top: 1px solid #eee; }
	.bd-bottom{ border-bottom: 1px solid #eee; }
	.vcenter{
		display: flex;
		align-items: center;
	}
</style>
